﻿using System;
using System.Web.Configuration;
using Mollie.iDEAL;
using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Interfaces;
using SuperSimpleWebshop.Domain.Repositories;
using umbraco;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;

namespace SuperSimpleWebshop.Payment.Mollie
{
    public class MolliePaymentResponseHandler : IPaymentResponseHandler
    {
        #region IPaymentResponseHandler Members
        IOrderRepository _OrderRepository = new OrderRepository();

        public string GetName()
        {
            return "Mollie";
        }

        public string HandlePaymentResponse()
        {
            try
            {
                //Mollie gives us the transaction Id.
                string transactionId = library.Request("transaction_id");

                if (!string.IsNullOrEmpty(transactionId))
                {
                    var order = this._OrderRepository.GetOrderByPaymentTransactionId(transactionId);

                    Document sender = order.Document;

                    var helper = new PaymentConfigHelper(GetName());

                    IdealCheck idealCheck = new IdealCheck(helper.Settings["partnerId"], helper.TestModeEnabled, transactionId);
                    if (idealCheck.Error)
                    {
                        order.OrderInfo.Status = OrderStatus.Payment_Failed;
                        order.OrderInfo.PaymentInfo.PaymentErrorMessage = idealCheck.ErrorMessage;
                    }

                    if (idealCheck.Payed)
                    {
                        order.OrderInfo.Status = OrderStatus.Ready_for_Dispatch;
                    }
                    else
                    {
                        order.OrderInfo.Status = OrderStatus.Payment_Failed;
                    }

                    order.Save();
                }
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, 0, "MolliePaymentResponseHandler.HandlePaymentResponse: " + ex.ToString());
            }

            return null;
        }
        #endregion
    }
}
